export default {
  data () {
    return {
      rolesList: [],
      dialogRolesVisible: false,
      rightsTree: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      rolsId: -1
    }
  },
  created () {
    this.mlLoadRolesList()
    this.mlLoadRightsList()
  },
  methods: {
    indexMethod (index) {
      return index
    },
    // 获取角色列表数据
    async mlLoadRolesList () {
      const res = await this.$axios.get('/roles')
      // console.log(res)
      this.rolesList = res.data.data
    },
    // 弹出分配授权对话框
    showRolesDialog (curRols) {
      this.rolsId = curRols.id

      this.dialogRolesVisible = true
      // 选中第三个
      // 报错 :  Cannot read property 'setCheckedKeys' of undefined"
      // this.$refs.tree.setCheckedKeys([105])

      let checkedKeys = []

      curRols.children.forEach(item1 => {
        item1.children.forEach(item2 => {
          item2.children.forEach(item3 => {
            checkedKeys.push(item3.id)
          })
        })
      })

      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(checkedKeys)
      })
    },
    // 请求权限数据
    async mlLoadRightsList () {
      const res = await this.$axios.get('rights/tree')
      console.log(res)
      this.rightsTree = res.data.data
    },
    // 分配权限
    async assignRights () {
      // 1. 获取全选的key
      const keys1 = this.$refs.tree.getCheckedKeys()
      const keys2 = this.$refs.tree.getHalfCheckedKeys()
      const keys = [...keys1, ...keys2]
      console.log(keys)

      const res = await this.$axios.post(`/roles/${this.rolsId}/rights`, {
        rids: keys.join(',')
      })
      console.log(res)

      // 1. 关闭对话框
      this.dialogRolesVisible = false
      // 2. 更新列表
      this.mlLoadRolesList()
      // 3. 弹出消息
      this.$message({
        type: 'success',
        message: res.data.meta.msg
      })
    }
  }
}
